package com.stars.easyms.schedule.core;

import com.stars.easyms.schedule.bean.DbScheduleServer;
import com.stars.easyms.schedule.constant.DistributedScheduleConstants;
import com.stars.easyms.schedule.service.DistributedScheduleService;

/**
 * 分布式调度框架的心跳线程：
 *      为了降低对其他插件的依赖性使用数据库作为心跳服务器
 *      为了保证心跳不被其他因素影响，该线程只做心跳工作，不处理其他工作
 *
 * @author guoguifang
 */
class DistributedScheduleHeartbeat extends AbstractDistributedScheduleThread {

    /**
     * 心跳参数
     */
    private final DbScheduleServer heartbeatParam = new DbScheduleServer();

    @Override
    protected void execute() {
        // 记录当次任务开始时间，保证心跳间隔稳定持续
        long startTimeMillis = System.currentTimeMillis();

        // 心跳开始
        int updateCount = DistributedScheduleService.getInstance().heartbeat(heartbeatParam);
        if (updateCount == 0) {
            DistributedScheduleService.getInstance().insertDbScheduleServer(getDistributedScheduleServerConfig());
        }

        // 心跳间隔，如果本地操作用时超过默认心跳时间那么不等待直接进行下一次心跳
        long usedTimeMillis = System.currentTimeMillis() - startTimeMillis;
        if (usedTimeMillis < DistributedScheduleConstants.DEFAULT_HEARTBEAT_INTERVAL_MILLI) {
            awaitIdleMillis(DistributedScheduleConstants.DEFAULT_HEARTBEAT_INTERVAL_MILLI - usedTimeMillis);
        }
    }

    private static DistributedScheduleHeartbeat singleInstance;

    static DistributedScheduleHeartbeat getSingleInstance() {
        if (singleInstance == null) {
            synchronized (DistributedScheduleHeartbeat.class) {
                if (singleInstance == null) {
                    singleInstance = new DistributedScheduleHeartbeat();
                }
            }
        }
        return singleInstance;
    }

    private DistributedScheduleHeartbeat(){
        super();
    }

}
